# coding=utf-8
"""
作者：董新强 
创建时间：2016-01-01
描述：测试基类
"""
import json
import time

import requests


class HttpHelper():
    def __init__(self):
        self.session = requests.Session()
        self.start_time = time.time()

    def post(self, host, url, post_data, authorization=''):
        self.start_time = time.time()
        result = self.session.post(host + url, json=post_data, headers={'Authorization': authorization})
        return self._response('POST', result, url)

    def get(self, host, url, payload: dict, authorization=''):
        self.start_time = time.time()
        if payload:
            ls = ['{}={}'.format(k, v) for k, v in payload.items()]
            params = '&'.join(ls)
            if '?' in host:
                url = url + '&' + params
            else:
                url = url + '?' + params

        result = self.session.get(host + url, headers={'Authorization': authorization})
        return self._response('GET', result, url)

    def put(self, host, url, post_data, authorization=''):
        self.start_time = time.time()
        result = self.session.put(host + url, data=post_data, headers={'Authorization': authorization})
        return self._response('PUT', result, url)

    def delete(self, host, url, data: dict = None, authorization=''):
        self.start_time = time.time()

        params = '&'.join([f'{k}={v}' for k, v in data.items()]) if data else ''
        if params:
            if '?' in url:
                url = f'{url}&{params}'
            else:
                url = f'{url}?{params}'

        result = self.session.delete(host + url, headers={'Authorization': authorization})
        return self._response('DEL', result, url)

    def upload(self, host, url, local_fpath, post_data=None, authorization=''):
        self.start_time = time.time()
        if not post_data: post_data = {}
        with  open(local_fpath, 'rb') as f:
            result = self.session.post(host + url, post_data, files={'file': f}, headers={'Authorization': authorization})
            return self._response('上传', result, url)

    def _response(self, method, result, url):

        cost, headers = '%.4f' % (time.time() - self.start_time), dict(result.headers)
        headers["【Http状态码】"] = result.status_code
        if result.status_code != 200:
            try:
                content = result.content
                if not content or isinstance(content, str):
                    return content, cost, headers

                dic = json.loads(result.content.decode(encoding='utf-8'))
                dic['status_code'] = result.status_code
                return dic, cost, headers
            except:
                return '【失败】\t\t' + method + '\t\t' + str(result.status_code), cost, headers

        return result.json(), cost, headers


if __name__ == '__main__':
    pass
